/*
 * Copyright (c) 2016. For Intelligent Group.
 */

package com.intelligent.mts.da.handler;


import com.intelligent.mts.da.utils.MessagesUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Julia.Zhou on 2016/07/20.
 */
public class DataHandler extends ChannelInboundHandlerAdapter {

	private int flowId;

	public static Logger logger = LoggerFactory.getLogger(DataHandler.class);

	public DataHandler(int flowId) {
		this.flowId = flowId;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("reading----" + msg);
		//String data = "2130;OBC;"+ MessagesUtils.getCurrentProcessData(flowId)+";OK/NG#";
		String data = "2010;OBC;"+ MessagesUtils.getCurrentResultData(flowId)+"OK#";
		ctx.writeAndFlush(data);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warn("Unexpected exception from com.intelligent.mts.da.handler " + cause);
		ctx.fireExceptionCaught(cause);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
		if (!(evt instanceof IdleStateEvent)) {
			return;
		}

		IdleStateEvent e = (IdleStateEvent) evt;
		if (e.state() == IdleState.ALL_IDLE) {
			// The connection was OK but there was no traffic for last period.
			logger.error("Disconnecting due to no inbound traffic");
			ctx.close();
		}
	}

}
